package com.yanxibao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanxibao.bean.User;
import com.yanxibao.common.Result;
import com.yanxibao.dto.LoginDTO;
import com.yanxibao.dto.UserDTO;
import com.yanxibao.dto.UserSearchDTO;
import com.yanxibao.mapper.UserMapper;
import com.yanxibao.service.UserService;
import com.yanxibao.util.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.yanxibao.util.RedisConstants.LOGIN_USER_KET;
import static com.yanxibao.util.RedisConstants.LOGIN_USER_TTL;
import static com.yanxibao.util.WechatPatterns.APPID;
import static com.yanxibao.util.WechatPatterns.APP_SECRET;


/**
 * 用户;(_user)表服务实现类
 * @author : http://www.chiner.pro
 * @date : 2022-9-25
 */
@Service
@Repository
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    private final static Integer PAGE_SIZE = 10;

    @Resource
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 用户登录功能
     * @param loginDTO
     * @return
     */
    public Result<UserDTO> login(LoginDTO loginDTO) {
        RestTemplate restTemplate = new RestTemplate();
        String code = loginDTO.getCode();
        String nickName = loginDTO.getNickName();
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + APPID +
                "&secret=" + APP_SECRET +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        String jsonData = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        if (StringUtils.contains(jsonData, "errcode")) {
            //出错了
            return Result.error("01000", "出错了！");
        }
        String openId = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
//        String unionid = jsonObject.getString("unionid");
        User user = userMapper.selectById(openId);
        User user1 = new User();
        user1.setUserId(openId);
        user1.setUserName(nickName);
        if (user != null) {
            userMapper.updateById(user1);
        } else {
            userMapper.insert(user1);
        }
        User user2 = userMapper.selectById(openId);
        UserDTO userDTO = BeanUtil.copyProperties(user2, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, true, true);
        String key = LOGIN_USER_KET + sessionKey;
        stringRedisTemplate.opsForHash().putAll(key, userMap);
        // 设置token过期时间
        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.DAYS);
        userDTO.setToken(sessionKey);
        return Result.success();
    }

    /**
     * 查询用户信息
     * @param id
     * @return
     */
    @Override
    public Result<User> selectUserById(String id) {
        User user = userMapper.selectById(id);
        return user == null ? Result.error("01010", "用户不存在！") : Result.success(user);
    }

    /**
     * 管理员分页和条件查询用户信息
     * @param currentSize
     * @param userSearchDTO
     * @return
     */
    @Override
    public Result<IPage<User>> paginQuery(Integer currentSize, UserSearchDTO userSearchDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(!userSearchDTO.isEmpty()){
            Map<String, Object> userSearchMap = BeanUtil.beanToMap(userSearchDTO, true, true);
            userSearchMap.forEach((key,value)->{
                switch (key){
                    case "user_specialized":
                        queryWrapper.eq(key,value);
                        break;
                    case "register_begin":
                        queryWrapper.ge("user_register",value);
                        break;
                    case "register_end":
                        queryWrapper.le("user_register",value);
                        break;
                    case "collection_min":
                        queryWrapper.ge("user_collection",value);
                        break;
                    case "collection_max":
                        queryWrapper.le("user_collection",value);
                        break;
                    case "history_min":
                        queryWrapper.ge("user_history",value);
                        break;
                    case "history_max":
                        queryWrapper.le("user_history",value);
                        break;
                    default:
                        break;
                }
            });
        }
        IPage<User> page = new Page<>(currentSize, PAGE_SIZE);
        IPage<User> page1 = userMapper.selectPage(page, queryWrapper);
        return page1.getTotal() == 0 ? Result.error("01020","未查询到数据") : Result.success(page1);
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @Override
    public Result<User> updateUser(User user) {
        UserDTO userDTO = UserHolder.getUser();
        User user1 = userMapper.selectById(userDTO.getUserId());
        if(user1 == null){
            return Result.error("01040","用户不存在！");
        }
        user.setUserId(userDTO.getUserId());
        userMapper.updateById(user);
        return Result.success();
    }

    /**
     * 删除用户信息
     * @param userId
     * @return
     */
    @Override
    public Result<Boolean> deleteUserById(String userId) {
        User user = userMapper.selectById(userId);
        if(user == null){
            return Result.error("01050","用户不存在！");
        }
        userMapper.deleteById(userId);
        return Result.success();
    }


}